package com.example.image.glide

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.LibraryGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * Author: Jason Zhang
 * Date: 2025/1/13
 * Desc: 使用OKHttp的网络缓存设置，为Glide提供网络缓存目录
 */
@GlideModule
class OkHttpModule: LibraryGlideModule(){

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
        var builder = OkHttpClient.Builder()
        //外部SD的目录
        var externalDir = Environment.getExternalStorageDirectory()
        if (externalDir.exists()){
            var cacheDir = "${externalDir.absolutePath}/cacheImages"
            var cacheFile = File(cacheDir)
            if (!cacheFile.exists()){
                cacheFile = File(cacheDir)
            }

            //设置缓存对象
            var cacheSize = 50 * 1024 * 1024L
            externalDir.totalSpace?.let {
                cacheSize = it / 8L
            }

            var cache = Cache(cacheFile, cacheSize)
            builder.cache(cache)
        }
        //内部SD的目录
        else{
            var internalCacheDir = "${context.externalCacheDir?.absolutePath}/cacheImage"
            var cacheFile = File(internalCacheDir)
            if (!cacheFile.exists()){
                cacheFile = File(internalCacheDir)
            }

            //设置缓存对象
            var cacheSize = 50 * 1024 * 1024L
            context.externalCacheDir?.totalSpace?.let {
                cacheSize = it / 8L
            }

            var cache = Cache(cacheFile, cacheSize)
            builder.cache(cache)
        }

        //替换Glide中OKHttpClient对象
        var newOkhttpClient = builder.build()
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(newOkhttpClient))

    }

}